package com.front.managementfront.driver.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.front.managementfront.driver.entity.CarInfo;
import com.front.managementfront.driver.entity.CertificateImg;
import com.front.managementfront.driver.entity.HktsDriver;
import com.front.managementfront.driver.entity.HktsRealNameAuthentication;
import com.front.managementfront.driver.mapper.CarInfoMapper;
import com.front.managementfront.driver.mapper.CertificateImgMapper;
import com.front.managementfront.driver.mapper.HktsDriverMapper;
import com.front.managementfront.driver.mapper.HktsRealNameAuthenticationMapper;
import com.front.managementfront.driver.service.ICarInfoService;
import com.front.managementfront.driver.service.IHktsDriverService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.front.managementfront.driver.vo.CarInfoListVo;
import com.front.managementfront.driver.vo.DriverParameterVo;
import com.front.managementfront.driver.vo.ManagementMobileVo;
import com.front.managementfront.fegin.IUserAppServiceClient;
import com.hkts.management.common.mq.FanoutRabbitConfig;
import com.hkts.management.common.utils.CustomPage;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.vo.UserAndRealNameVo;
import com.hkts.management.common.vo.UserBasicInfoVo;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.web.bind.annotation.RequestBody;

import javax.print.attribute.standard.RequestingUserName;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2021-04-22
 */
@Service
@Transactional
public class HktsDriverServiceImpl extends ServiceImpl<HktsDriverMapper, HktsDriver> implements IHktsDriverService {

    @Autowired
    private IUserAppServiceClient iUserAppServiceClient;
    @Autowired
    private HktsDriverMapper hktsDriverMapper;

    @Autowired
    private HktsRealNameAuthenticationMapper hktsRealNameAuthenticationMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private CarInfoMapper carInfoMapper;
    @Autowired
    private CertificateImgMapper certificateImgMapper;

    @Autowired
    public ICarInfoService iCarInfoService;
    @Override
    public IPage<HktsDriver> selectPage(Page<HktsDriver> page, HktsDriver hktsDriver) {
        QueryWrapper<HktsDriver> query = Wrappers.query();
        QueryWrapper<HktsDriver> entityWrapper = getEntityWrapper(query, hktsDriver);
        return hktsDriverMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HktsDriver> selectList(HktsDriver hktsDriver) {
        QueryWrapper<HktsDriver> query = Wrappers.query();
        QueryWrapper<HktsDriver> entityWrapper = getEntityWrapper(query, hktsDriver);
        return hktsDriverMapper.selectList(entityWrapper);
    }

    @Override
    public UserAndRealNameVo getDriverInfoByUserId(String userId) {
        UserAndRealNameVo vo=  hktsDriverMapper.getDriverInfoByUserId(userId);
        if (vo!= null && vo.getApproval().equals("2")){
            QueryWrapper<CarInfo> query = Wrappers.query();
            query.lambda().eq(CarInfo::getUserId, userId);
            query.lambda().eq(CarInfo::getApprovalStatus,1);
            query.lambda().eq(CarInfo::getDelFlag, 0);
            query.lambda().eq(CarInfo::getIsAuto,0);
            CarInfo carInfo = carInfoMapper.selectOne(query);
            vo.setCarCode(carInfo.getCarCode());
            vo.setVehicleLength(carInfo.getVehicleLength());
            vo.setEhicleType(carInfo.getEhicleType());
            QueryWrapper<CertificateImg> queryCertificateImg = Wrappers.query();
            queryCertificateImg.lambda().eq(CertificateImg::getUserId, userId)
                    .eq(CertificateImg::getCarId, 0)
                    .eq(CertificateImg::getDelFlag,0);
            List<CertificateImg> certificateImgs = certificateImgMapper.selectList(queryCertificateImg);
            if (certificateImgs.size() > 0){
                Map<String, Object> collect1 = certificateImgs.stream().collect(Collectors.toMap(CertificateImg::getCertificateType, Function.identity()));
                /*Map<String, Object> collect2 = certificateImgs.stream().collect(Collectors.toMap( t ->{ return t.getCertificateType();},CertificateImg::getCardPath));*/
                vo.setApprovalUrl(collect1);
            }
        }
        return vo;
    }

    @Override
    public List<UserAndRealNameVo> getDriverInfosByUserIds(List<String> userIds) {
       List<UserAndRealNameVo>  vo=  hktsDriverMapper.getDriverInfosByUserIds(userIds);

        return vo;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsDriver> getEntityWrapper(QueryWrapper<HktsDriver> entityWrapper, HktsDriver hktsDriver) {
        //条件拼接
        if (StringUtils.isNotBlank(hktsDriver.getCreateBy())) {
            entityWrapper.like(HktsDriver.CREATE_BY, hktsDriver.getCreateBy());
        }
                /*if(StringUtils.isNotBlank(hktsDriver.getCreateTime())){
                entityWrapper.like(HktsDriver.CREATE_TIME,hktsDriver.getCreateTime());
                }
                if(StringUtils.isNotBlank(hktsDriver.getDelFlag())){
                entityWrapper.like(HktsDriver.DEL_FLAG,hktsDriver.getDelFlag());
                }*/
        if (StringUtils.isNotBlank(hktsDriver.getUpdateBy())) {
            entityWrapper.like(HktsDriver.UPDATE_BY, hktsDriver.getUpdateBy());
        }
                /*if(StringUtils.isNotBlank(hktsDriver.getUpdateTime())){
                entityWrapper.like(HktsDriver.UPDATE_TIME,hktsDriver.getUpdateTime());
                }*/
        if (StringUtils.isNotBlank(hktsDriver.getApproval())) {
            entityWrapper.like(HktsDriver.APPROVAL, hktsDriver.getApproval());
        }
        if (StringUtils.isNotBlank(hktsDriver.getIsCaptain())) {
            entityWrapper.like(HktsDriver.IS_CAPTAIN, hktsDriver.getIsCaptain());
        }
        if (StringUtils.isNotBlank(hktsDriver.getMobile())) {
            entityWrapper.like(HktsDriver.MOBILE, hktsDriver.getMobile());
        }
        if (StringUtils.isNotBlank(hktsDriver.getPassStrength())) {
            entityWrapper.like(HktsDriver.PASS_STRENGTH, hktsDriver.getPassStrength());
        }
        if (StringUtils.isNotBlank(hktsDriver.getPassWord())) {
            entityWrapper.like(HktsDriver.PASS_WORD, hktsDriver.getPassWord());
        }
        if (StringUtils.isNotBlank(hktsDriver.getStatus())) {
            entityWrapper.like(HktsDriver.STATUS, hktsDriver.getStatus());
        }
        if (StringUtils.isNotBlank(hktsDriver.getUserName())) {
            entityWrapper.like(HktsDriver.USER_NAME, hktsDriver.getUserName());
        }
        return entityWrapper;
    }

    @Override
    public void updateDriverApproval( DriverParameterVo vo) {
        HktsDriver hktsDriver = hktsDriverMapper.selectById(vo.getUserId());
        if(hktsDriver.getApproval().equals(vo.getApproval())){
            throw new RuntimeException("认证状态已经修改！");
        }
        hktsDriverMapper.updateDriverApproval(vo);
        QueryWrapper<CarInfo> entityWrapper=new QueryWrapper<CarInfo>();
        entityWrapper.lambda().eq(CarInfo::getUserId,hktsDriver.getId());
        entityWrapper.lambda().eq(CarInfo::getDelFlag,0);
        CarInfo one = iCarInfoService.getOne(entityWrapper);
        if(vo.getApproval().equals("2")){
            one.setApprovalStatus(1);
        }else{
            one.setApprovalStatus(2);
        }
        one.setApprovalType(1);
        Result<UserBasicInfoVo> userBasicInfoVoResult1 = iUserAppServiceClient.remoteUserBasicInfo();
        one.setApprovalUser(userBasicInfoVoResult1.getResult().getId());
        one.setApprovalTime(LocalDateTime.now());
        iCarInfoService.updateById(one);
        //修改更新时间
        Result<UserBasicInfoVo> userBasicInfoVoResult = iUserAppServiceClient.remoteUserBasicInfo();
        vo.setApprovalUser(userBasicInfoVoResult.getResult().getId());
        hktsRealNameAuthenticationMapper.updateApprovalTime(vo);
        Map<String,Object> map=new HashMap<String,Object>();//
        map.put("siteId", 3);
        map.put("userId", vo.getUserId());
        map.put("templateData", vo.getApproval());
        amqpTemplate.convertAndSend(FanoutRabbitConfig.FANOUTEXCHANGE, null, map);
    }

    @Override
    public void updateDriverStatus(DriverParameterVo vo) {

        hktsDriverMapper.updateDriverStatus(vo);

    }

    @Override
    public HktsDriver getDriverByUserNameOrMobile(String userName){
        QueryWrapper<HktsDriver> query = Wrappers.query();

        if (StringUtils.isNotBlank(userName)) {
            query.lambda().eq(HktsDriver::getMobile,userName).or().eq(HktsDriver::getUserName,userName);
        }
        HktsDriver hktsDriver = hktsDriverMapper.selectOne(query);
        return hktsDriver;
    }

    @Override
    public List<HktsDriver> getDriversByUserNameOrMobile(String userName) {
        QueryWrapper<HktsDriver> query = Wrappers.query();
        if (StringUtils.isNotBlank(userName)) {
            query.lambda().like(HktsDriver::getMobile,userName).or().like(HktsDriver::getUserName,userName);
        }
        List<HktsDriver> hktsDrivers = hktsDriverMapper.selectList(query);
        return hktsDrivers;
    }

    @Override
    public CustomPage getDriverInfoByMobile(CustomPage page,String mobile) {
        ManagementMobileVo mobileVo = new ManagementMobileVo();
        mobileVo.setMobile(mobile);
        mobileVo.setFirstRow(page.getFirstRow());
        mobileVo.setLastRow(page.getLastRow());
        List<UserAndRealNameVo> driverInfoByMobile = hktsDriverMapper.getDriverInfoByMobile(mobileVo);
        page.setResultData(driverInfoByMobile);
        page.setTotalRows((long) driverInfoByMobile.size());
        return page;
    }
}
